package com.common.basic.base;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.displaytag.tags.TableTagParameters;
import org.displaytag.util.ParamEncoder;
import org.jsecurity.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.Validator;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import com.common.basic.util.Globals;
import com.common.basic.util.PageDto;

public abstract class BaseController {
	private static final transient org.apache.commons.logging.Log LOGGER = org.apache.commons.logging.LogFactory
			.getLog(BaseController.class);
	
	@Autowired
	protected ResourceBundleMessageSource messageSource;
	
	@Autowired
	protected SessionLocaleResolver localeResolver;
	
	@Autowired
	protected Validator validator;	
	
	protected PageDto getPage(HttpServletRequest request){
		String pgIdx = request.getParameter(Globals.PAGE_INDEX)!=null?request.getParameter(Globals.PAGE_INDEX):"1";
		String pgRow = request.getParameter(Globals.PAGE_ROWS)!=null?request.getParameter(Globals.PAGE_ROWS):"10";
		return new PageDto(Integer.parseInt(pgIdx), Integer.parseInt(pgRow));
	}
	
	protected void sendError(HttpServletResponse response, String msg){
		try{
			PrintWriter out = response.getWriter();
			out.println("[error]:"+msg);
			out.flush();
			out.close();
		}catch(IOException ioe){}
	}
	
	protected void sendWarning(HttpServletResponse response, String msg){
		try{
			PrintWriter out = response.getWriter();
			out.println("[warning]:"+msg);
			out.flush();
			out.close();
		}catch(IOException ioe){}
	}
	
	@SuppressWarnings("unchecked")
	protected boolean hasFieldErrors(HttpServletRequest request, HttpServletResponse response, BindingResult result){
		boolean hasErrors = result.hasErrors();
		if(hasErrors){
			StringBuilder msg = new StringBuilder();
			for(Iterator<FieldError> i = result.getFieldErrors().iterator(); i.hasNext();){
				FieldError f = i.next();
				msg.append("- ").append(getMessage(request, f.getCode(), f.getArguments())).append("<br/>");
			}
			sendWarning(response, msg.toString());
		}
		return hasErrors;
	}
	
	protected String getMessage(HttpServletRequest request, String code, Object[] args){
		return messageSource.getMessage(code, args, getLocale(request));
		
    }
	
	protected String getMessage(HttpServletRequest request, String code){
		return getMessage(request, code, null);
    }
	
	protected Locale getLocale(HttpServletRequest request){
		return localeResolver.resolveLocale(request);
	}
	
	protected void setValidator(Validator validator) {
		this.validator = validator;
	}
	
	protected String getOrderDispTag(HttpServletRequest request){
		String result = null;
		String sortColoumnDT = request.getParameter(new ParamEncoder("row").encodeParameterName(TableTagParameters.PARAMETER_SORT));
		String SortTypeDT = request.getParameter(new ParamEncoder("row").encodeParameterName(TableTagParameters.PARAMETER_ORDER));
		if(sortColoumnDT!=null && !sortColoumnDT.equals(""))
			result = (sortColoumnDT + " " + (SortTypeDT!=null&&SortTypeDT.equals("2")?"ASC":"DESC"));
		return result;
	}
	
	protected String getRequestValidation(HttpServletRequest request, HttpServletResponse response){
		//* security validation
		if (!(Boolean) SecurityUtils.getSubject().getSession().getAttribute(Globals.ERROR_REQUESTED_LINK)) {
			SecurityUtils.getSubject().getSession().removeAttribute(Globals.ERROR_REQUESTED_LINK);
			sendError(response, getMessage(request, "error.permissionDenied",
					new String[] { (String) SecurityUtils.getSubject()
							.getSession().getAttribute(
									Globals.CURRENT_USER_NAME) }));
			return null;
		}
		return "valid";
	}
	
	protected void setNormalTimeout(HttpServletRequest request){
		LOGGER.debug(">>>>BaseController.setNormalTimeout");
		request.getSession().setMaxInactiveInterval(Integer.parseInt(getMessage(request, Globals.STD_SESSION_TIME)) * 60);
	}

	protected void setLongTimeout(HttpServletRequest request){
		LOGGER.debug(">>>>BaseController.setLongTimeout");
		request.getSession().setMaxInactiveInterval(Integer.parseInt(getMessage(request, Globals.LONG_SESSION_TIME)) * 60);
	}
}